package crontab

import (
	"context"
	"fmt"
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/util/syscall"
	"github.com/google/uuid"
)

// AddUser 添加用户任务
func (cls *Crontab) AddUser(schedule string, command string, args []string) error {
	cls.mutex.Lock()
	defer cls.mutex.Unlock()

	var task = &Task{Id: uuid.New().String(), Schedule: schedule, Command: command, Args: args}
	cls.user = append(cls.user, task)

	if err := cls.sync(); nil != err {
		return err
	}

	id, err := cls.cron.AddFunc(schedule, func() {
		if _, err := syscall.ExecuteCommandGetOutputIgnoreQuitCode(context.Background(), task.Command, task.Args...); nil != err {
			logger.GetLogger().Sugar().Errorf("执行定时任务失败，失败原因: %s，任务ID: %s", err, task.Id)
		}
	})

	if nil != err {
		return fmt.Errorf("任务创建成功但启动失败，失败原因: %s", err)
	}

	task.EntryId = id

	return nil
}
